package com.yunhe.abnormal.service.base.impl;

import com.yunhe.abnormal.domain.base.AbnormalFormat;
import com.yunhe.common.exception.ArgumentErrorException;
import com.yunhe.abnormal.mapper.base.AbnormalFormatMapper;
import com.yunhe.common.model.base.AbnormalFormatDTO;
import com.yunhe.abnormal.repository.base.AbnormalDetailFormatRepository;
import com.yunhe.abnormal.service.base.AbnormalDetailFormatService;
import com.yunhe.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class AbnormalDetailFormatServiceImpl implements AbnormalDetailFormatService {

    @Autowired
    private AbnormalDetailFormatRepository abnormalDetailFormatRepository;
    @Autowired
    private AbnormalFormatMapper abnormalFormatMapper;

    private void processBeforeSave(AbnormalFormat format)
            throws ArgumentErrorException{
        if (StringUtil.isEmpty(format.getContent())) {
            throw new ArgumentErrorException("内容不得为空");
        }
    }

    @Override
    public AbnormalFormatDTO create(AbnormalFormat abnormalFormat) throws ArgumentErrorException {
        processBeforeSave(abnormalFormat);
        AbnormalFormat result = abnormalDetailFormatRepository.save(abnormalFormat);
        return abnormalFormatMapper.to(result);
    }

    @Override
    public void delete(Long id) {
        abnormalDetailFormatRepository.deleteById(id);
    }

    @Override
    public AbnormalFormatDTO update(Long id,
                                 Optional<Long> code,
                                 Optional<String> name,
                                 Optional<String> title,
                                 Optional<String> content) throws ArgumentErrorException {
        AbnormalFormat byId = abnormalDetailFormatRepository.findById(id).orElse(null);
        if (byId == null) {
            //TODO
            return null;
        }
        code.ifPresent(byId::setCode);
        name.ifPresent(byId::setName);
        title.ifPresent(byId::setTitle);
        content.ifPresent(byId::setContent);
        processBeforeSave(byId);
        AbnormalFormat result = abnormalDetailFormatRepository.save(byId);
        return abnormalFormatMapper.to(result);
    }

    @Override
    public AbnormalFormatDTO findById(Long id) {
        AbnormalFormat result = abnormalDetailFormatRepository.findById(id).orElse(null);
        return abnormalFormatMapper.to(result);
    }

    @Override
    public Iterable<AbnormalFormatDTO> findAbnormalDetailFormats() {
        List<AbnormalFormat> result = (List<AbnormalFormat>) abnormalDetailFormatRepository.findAll();
        return abnormalFormatMapper.to(result);
    }

    @Override
    public void bind(Long id, Long pid) {
        abnormalDetailFormatRepository.bind(id, pid);
    }
}
